//
//  PlayerAudioListViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/2.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let audioCellIdentifier = "AudioTableCell"
private let opButtonsCellIdentifier = "PlayAudioListOpCell"

class PlayerAudioListViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var audios: [Audio]? = NowPlayingManager.shared.getAudioList()
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: audioCellIdentifier, bundle: nil), forCellReuseIdentifier: audioCellIdentifier)
    tableView.contentInset = UIEdgeInsets.init(top: 20, left: 0, bottom: 40, right: 0)
    tableView.scrollIndicatorInsets = tableView.contentInset
  }
  
  private func setDownloadAllButtonState(opCell: PlayAudioListOpCell) {
    if let notDownloadedAudios = (audios?.filter { $0.localURL == nil }),
      notDownloadedAudios.count > 0 {
      opCell.isDownloadAllButtonHidden = false
    } else {
      opCell.isDownloadAllButtonHidden = true
    }
  }
  
  private func addNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(downloadFinished(notifiation:)), name: .downloadFinished, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(streamingCacheFinished), name: .streamingCacheFinished, object: nil)
  }
  
  @objc private func downloadFinished(notifiation: Notification) {
    if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? PlayAudioListOpCell {
      setDownloadAllButtonState(opCell: cell)
    }
  }
  
  @objc private func streamingCacheFinished() {
    if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? PlayAudioListOpCell {
      setDownloadAllButtonState(opCell: cell)
    }
  }
  
  // MARK: - Public vars
  

  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    addNotifications()
    prepareUI()
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowAddToPlayListSegue" {
      let nav = segue.destination as! BaseNavigationController
      nav.dismissDelegate = self
      let addToPlayListStep1ViewController = nav.viewControllers.first as! AddToPlayListStep1ViewController
//      addToPlayListStep1ViewController.audios = getSortedAudios(sortType: audioSortType)
      addToPlayListStep1ViewController.audios = audios
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  deinit {
    NotificationCenter.default.removeObserver(self)
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

// MARK: - UITableViewDataSource

extension PlayerAudioListViewController: UITableViewDataSource {
  
  func numberOfSections(in tableView: UITableView) -> Int {
    return 2
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0:
      return 1
    case 1:
      return audios?.count ?? 0
    default:
      return 0
    }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    switch indexPath.section {
    case 0:
      // op cell
      let cell = tableView.dequeueReusableCell(withIdentifier: opButtonsCellIdentifier, for: indexPath) as! PlayAudioListOpCell
      cell.delegate = self
      setDownloadAllButtonState(opCell: cell)
      
      return cell
  
    default:
      // audio cell
      let cell = tableView.dequeueReusableCell(withIdentifier: audioCellIdentifier, for: indexPath) as! AudioTableCell
//      if let audio = getSortedAudios(sortType: audioSortType)?[indexPath.row] {
      if let audio = audios?[indexPath.row] {
        cell.prepare(audio: audio)
      }
      return cell
    }
  }
}

// MARK: - UITableViewDelegate

extension PlayerAudioListViewController: UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.section == 1 {
      if let audio = audios?[indexPath.row],
        let album = audio.album {
        NowPlayingManager.shared.play(album: album, audio: audio)
      }
    }
    
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
  func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 44
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 0 {
      return UITableView.automaticDimension
    } else {
      return AudioTableCell.defaultHeight
    }
  }
}

// MARK: - BaseNavigationControllerDismissDelegate

extension PlayerAudioListViewController: BaseNavigationControllerDismissDelegate {
  func dismiss(navigationController: BaseNavigationController, completion: (() -> Void)?) {
    dismiss(animated: true, completion: completion)
  }
}

// MARK: - PlayAudioListOpCellDelegate

extension PlayerAudioListViewController: PlayAudioListOpCellDelegate {
  func downloadAllAudios() {
    if let audios = self.audios {
      audios.forEach {
        if $0.localURL == nil && AudioDownloadManager.shared.audioIsInQueue($0) == false {
          AudioDownloadManager.shared.add(audio: $0)
        }
      }
    }
  }
}
